package com.aces2win.server.entities;

import java.util.Date;

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import com.aces2win.shared.beans.TradeBean;

@PersistenceCapable
public class Trade {
	@Persistent
	private Date openDate;
	@Persistent
	private Date closeDate;
	@Persistent
	private double openAmount;
	@Persistent
	private double closeAmount;
	@Persistent
	private double maxDrawDawn=0;
	@Persistent
	private double volume;
	@Persistent
	private boolean isLong;
	
	public Date getOpenDate() {
		return openDate;
	}
	public void setOpenDate(Date openDate) {
		this.openDate = openDate;
	}
	public Date getCloseDate() {
		return closeDate;
	}
	public void setCloseDate(Date closeDate) {
		this.closeDate = closeDate;
	}
	public double getOpenAmount() {
		return openAmount;
	}
	public void setOpenAmount(double openAmount) {
		this.openAmount = openAmount;
	}
	public double getCloseAmount() {
		return closeAmount;
	}
	public void setCloseAmount(double closeAmount) {
		this.closeAmount = closeAmount;
	}
	public boolean isLong() {
		return isLong;
	}
	public void setLong(boolean isLong) {
		this.isLong = isLong;
	}
	
	public void openTrade(Date d, double amount, boolean isLong){
		setOpenDate(d);
		setOpenAmount(amount);
		setLong(isLong);
	}
	
	public void closeTrade(Date d, double amount){
		setCloseDate(d);
		setCloseAmount(amount);
	}
	
	public double getBalance(){
		return getCloseAmount()-getOpenAmount();
	}
	public double getVolume() {
		return volume;
	}
	public void setVolume(double volume) {
		this.volume = volume;
	}
	
	public double getMaxDrawDawn() {
		return maxDrawDawn;
	}
	
	public void setMaxDrawDawn(double highOrLow) {
		if(isLong()){
			this.maxDrawDawn = Math.max(getMaxDrawDawn(), getOpenAmount()-highOrLow*getVolume());
		}else{
			this.maxDrawDawn = Math.max(getMaxDrawDawn(), highOrLow*getVolume()-getOpenAmount());
		}
		
	}
	
	public String toString(){
		String result = "Position "+(this.isLong()?"Long ":"Short ")+this.getOpenDate()+"@"+this.getOpenAmount();
		if(this.getCloseDate()!=null){
			double profitLoss = this.getCloseAmount()-this.getOpenAmount();
			result = result+" and Closed "+this.getCloseDate()+"@"+this.getCloseAmount()+"MaxDrawDawn :"+this.getMaxDrawDawn()+"Profit/Loss : "+profitLoss;
		}
		return result;
	}
	
	public TradeBean toBean(){
		TradeBean tb = new TradeBean();
		tb.setCloseAmount(getCloseAmount());
		tb.setCloseDate(getCloseDate());
		tb.setLong(isLong());
		tb.setMaxDrawDawn(getMaxDrawDawn());
		tb.setOpenAmount(getOpenAmount());
		tb.setOpenDate(getOpenDate());
		tb.setVolume(getVolume());
		
		return tb;
	}
}
